package com.whcoding.task.xxl.job.task.handler;

import com.google.common.collect.Lists;
import com.whcoding.task.xxl.job.po.OrmDeptPO;
import com.whcoding.task.xxl.job.task.base.TaskIJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@JobHandler(value = "trackTaskerHandler")
@Component
public class TrackTaskerHandler extends TaskIJobHandler {

    private static final Logger logger = LoggerFactory.getLogger(TrackTaskerHandler.class);

    @Autowired
    private TrackTasker trackTasker;

    /**
     * @description:
     * @author ZhouWenHao
     * @date 2023/04/04 9:15
     * @param:
     * @return: void
     */
    public void execute() {
        //获取上次执行完的id
        Long maxId = this.getMaxId();
        //获取本轮数据
        List<OrmDeptPO> result = getData(maxId);
        if (null == result || result.isEmpty()) {
            logger.warn("IOT[railway] 本轮没有获取到数据");
            return;
        }
        //推送给多线程任务执行器
        trackTasker.pushData(result);
        logger.info("IOT[railway] 任务推到线程池中");
        //更新最大id
        this.updateMaxId(result);
    }

    /**
     * 取最大的id
     *
     * @return
     */
    private Long getMaxId() {
        return 232065628L;
    }

    private List<OrmDeptPO> getData(Long maxId) {
        //获取一万条数据分两次
        List<OrmDeptPO> data = getDataHandler(maxId);
        if (CollectionUtils.isEmpty(data)) {
            return Lists.newArrayList();
        }
        return data;
    }


    /**
     * 获取需要处理的数据
     * @param maxId
     * @return
     */
    private List<OrmDeptPO> getDataHandler(Long maxId) {
        if (null == maxId) {
            return Lists.newArrayList();
        }
        List<OrmDeptPO> resultList = new ArrayList<>(16);
        //根据id进行排序
        return resultList.stream()
                .sorted(Comparator.comparing(OrmDeptPO::getId))
                .collect(Collectors.toList());
    }

    /**
     * 更新redis中最大id
     * @param result
     */
    private void updateMaxId(List<OrmDeptPO> result) {
        //获取最大id
        Optional<Integer> max = result.stream()
                .filter(o -> null != o.getId())
                .map(OrmDeptPO::getId)
                .max((a, b) -> a > b ? 1 : -1);
        //更新redis最大id
        if (max.isPresent()) {
            logger.debug("更新最大id完毕[{}]", max.get());
        } else {
            logger.error("更新最大id失败");
        }
    }

    /**
     * 任务入口
     * @param param
     */
    @Override
    public void doTask(String param) {
        execute();
    }


}
